﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;

namespace bdtheque.azure.business.azurestorage
{
    public class CloudQueueHelper
    {
        #region Private Members
        private CloudStorageAccount cloudStorageAccount;
        #endregion

        #region Constructors
        public CloudQueueHelper(CloudStorageAccount _cloudStorageAccount)
        {
            cloudStorageAccount = _cloudStorageAccount;
        }
        #endregion

        #region Public Methods
        public void AddMessage(string queueReference, string message)
        {
            // Create queue client
            var queueClient = cloudStorageAccount.CreateCloudQueueClient();
            queueClient.RetryPolicy = RetryPolicies.Retry(5, TimeSpan.FromSeconds(5));

            // Get queue reference
            var queue = queueClient.GetQueueReference(queueReference);

            // Add message
            var queueMessage = new CloudQueueMessage(message);
            queue.AddMessage(queueMessage);
        }

        public void DeleteMessage(CloudQueue queue, CloudQueueMessage message)
        {
            try
            {
                // Processing was successfully finished, delete message from Incoming Queue
                queue.DeleteMessage(message);
            }
            catch (StorageClientException ex)
            {
                if (ex.ExtendedErrorInformation.ErrorCode == "MessageNotFound")
                {
                     // Pop receipt must be invalid ignore or log (so we can tune the visibility timeout)
                }
                else
                {
                    throw;
                }
            }
        }
        #endregion
    }
}
